package main

import (
	"context"
	"fmt"
	"github.com/joho/godotenv"
	"github.com/sashabaranov/go-openai"
	"log"
	"os"
)

// go get github.com/sashabaranov/go-openai
// go get github.com/joho/godotenv

func NewOpenAiClient() *openai.Client {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	token := os.Getenv("TONGYI_API_KEY")
	dashscope_url := "https://dashscope.aliyuncs.com/compatible-mode/v1"
	config := openai.DefaultConfig(token)
	config.BaseURL = dashscope_url

	return openai.NewClientWithConfig(config)
}

func Chat(message []openai.ChatCompletionMessage) openai.ChatCompletionMessage {
	c := NewOpenAiClient()
	rsp, err := c.CreateChatCompletion(context.TODO(), openai.ChatCompletionRequest{
		Model:    "qwen-plus",
		Messages: message,
	})
	if err != nil {
		log.Println(err)
		return openai.ChatCompletionMessage{}
	}

	return rsp.Choices[0].Message
}

var MessageStore ChatMessages

type ChatMessages []openai.ChatCompletionMessage

func (cm *ChatMessages) AddFor(role string, msg string) {
	*cm = append(*cm, openai.ChatCompletionMessage{
		Role:    role,
		Content: msg,
	})
}

func (cm *ChatMessages) ToMessage() []openai.ChatCompletionMessage {
	ret := make([]openai.ChatCompletionMessage, len(*cm))
	for index, c := range *cm {
		ret[index] = c
	}
	return ret
}

var RoleSystem = "system"
var RoleUser = "user"
var RoleAssistant = "assistant"

func main1() {
	MessageStore.AddFor(RoleSystem, "你是一个足球领域的专家，请尽可能地帮我回答与足球相关的问题。")
	MessageStore.AddFor(RoleUser, "C罗是哪个国家的足球运动员？")
	MessageStore.AddFor(RoleAssistant, "C罗是葡萄牙足球运动员。")
	MessageStore.AddFor(RoleUser, "内马尔呢？")

	response := Chat(MessageStore.ToMessage())
	fmt.Println(response.Content)
}
